<!-- 到期设备 -->
<template>
  <div class="app-container">
    <div class="titleMolde">电子围栏
    </div>
    <div class="Filters">
      <el-input v-model="queryParams.fenceName" style="width: 200px" placeholder="电子围栏名称" />
      <el-button type="primary" class="mrg-lf-10" @click="handleQuery">查询</el-button>
      <el-button type="primary" class="mrg-lf-10" @click="addPageQuery" v-hasPerm="['ElectronicFence:add']">添加</el-button>
    </div>
    <el-table v-loading="loading" :data="pageData">
      <el-table-column label="序号" align="center" type="index" width="60" />
      <el-table-column label="围栏名称" align="center" prop="fenceName" />
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <!-- <el-table-column label="坐标集" align="center" prop="coordinateSet" /> -->
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" fixed="right" width="220">
        <template #default="scope">
          <el-button title="编辑" v-hasPerm="['ElectronicFence:edit']" type="primary" icon="edit" circle @click.prevent="editRow(scope.row)" />
          <el-button title="删除" v-hasPerm="['ElectronicFence:delete']" type="danger" icon="delete" circle @click.prevent="deleteRow(scope.row)" />
        </template>
      </el-table-column>
    </el-table>
    <pagination @pagination="handleQuery" v-if="queryParams.pages.total > 0" v-model:total="queryParams.pages.total"
      v-model:page="queryParams.pages.current" v-model:limit="queryParams.pages.size" />

  </div>
  <el-dialog destroy-on-close class="dialogTableVisibleclass" top="5vh" v-model="outerVisible" title="新增围栏"
    width="80vw">
    <div class="div-container">
      <div class="div-left-container">
        <div class="div_search fontColor_333">
          围栏编号
          <el-input v-model="addFences.fenceName" style="width: 200px" placeholder="围栏编号" />
          <el-button type="primary" class="mrg-lf-10">添加设备</el-button>
        </div>
      </div>
      <div class="div-right-container">
        <el-button type="primary" @click="createPolygon">新建</el-button>
        <div id="myPageTop">
          <ul>
            <li>
              <div>请输入关键字：</div>
            </li>
          </ul>
          <ul>
            <li>
              <input id="tipinput" />
            </li>
          </ul>
        </div>
        <div id="amap-maps" style="margin-top: 10px; width: 100%; height: 70vh; border: 1px solid #999;"></div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="info" @click="outerVisible = false">关闭</el-button>
        <el-button type="primary" @click="addSave">增加</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog destroy-on-close class="dialogTableVisibleclass" top="5vh" v-model="outerVisibleEdit" title="编辑围栏"
    width="80vw">
    <div class="div-container">
      <div class="div-left-container">
        <div class="div_search fontColor_333">
          围栏编号
          <el-input v-model="editFences.fenceName" style="width: 200px;" placeholder="围栏编号" />
          <el-button type="primary" class="mrg-lf-10">添加设备</el-button>
        </div>
      </div>
      <div class="div-right-container">

        <el-button type="primary" @click="createPolygon">新建</el-button>
        <div id="myPageTop">
          <ul>
            <li>
              <div>请输入关键字：</div>
            </li>
          </ul>
          <ul>
            <li>
              <input id="tipinput" />
            </li>
          </ul>
        </div>
        <div id="amap-maps" style="margin-top: 10px; width: 100%; height: 70vh; border: 1px solid #999;"></div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="info" @click="outerVisibleEdit = false">关闭</el-button>
        <el-button type="primary" @click="editSave">编辑</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { TabsPaneContext } from "element-plus";
import { initMap } from "@/common/map";
import LogAPI, { FencesPageQuery, addFencesPageQuery } from "@/api/log";
const props = defineProps({
  ld: {
    type: String,
    required: true,
  },
});
let customerId = props.ld
console.log('customerIdcustomerId', customerId);
// 监听 message 的变化 
watch(() => props.ld, (newMessage, oldMessage) => {
  console.log(66666666, newMessage, oldMessage);
  if (newMessage !== oldMessage) {
    console.log('chengg');
    queryParams.customerId = newMessage
    handleQuery()
  }

});
let _AMap: any = null;
let _map: any = null;
let polyEditor: any = null
let placeSearch: null | any = null
/**
@date: 2024-08-30 11:10:08
实例化地图
*/
async function setMap(coordinateSet: number[]) {
  const elements = document.querySelectorAll('.amap-sug-result');

  // 遍历这些元素并将其从 DOM 中移除
  elements.forEach(element => {
    element.remove();
  });
  let { AMap, map } = await initMap("amap-maps");
  _AMap = AMap;
  _map = map;

  var path1 = coordinateSet.length ? coordinateSet : corners
  var polygon = new _AMap.Polygon({
    path: path1
  })
  polyEditor = new _AMap.PolygonEditor(_map);
  _map.add(polygon);
  _map.setFitView();
  polyEditor.addAdsorbPolygons(polygon);
  polyEditor.on('add', function (data: any) {
    var polygon = data.target;
    polyEditor.addAdsorbPolygons(polygon);
    polygon.on('dblclick', () => {
      polyEditor.setTarget(polygon);
      polyEditor.open();
    })
  })
  polygon.on('dblclick', () => {
    polyEditor.setTarget(polygon);
    polyEditor.open();
  })
  _map.on('rightclick', function () {
    setTimeout(() => {
      polyEditor.close()
    }, 50);

  });
  polyEditor.setTarget(polygon);
  polyEditor.open();

  // 搜索框
  var autoOptions = {
    input: "tipinput"
  };
  var auto = new _AMap.AutoComplete(autoOptions);
  placeSearch = new _AMap.PlaceSearch({
    map: _map
  });  //构造地点查询类
  auto.on("select", select);//注册监听，当选中某条记录时会触发
}
function select(e: any) {
  console.log(e);

  placeSearch.setCity(e.poi.adcode);
  placeSearch.search(e.poi.name);  //关键字查询查询
}
function createPolygon() {
  _map.clearMap()
  polyEditor.clearAdsorbPolygons();
  polyEditor.close();
  polyEditor.setTarget();
  polyEditor.open();

}
/**
@date: 2024-08-31 14:55:16
新增电子围栏
*/
let outerVisible = ref(false);
/**
@date: 2024-08-31 14:55:01
编辑电子围栏
*/
let outerVisibleEdit = ref(false);
const loading = ref(false);

let pageData = ref()
/** 用户查询参数  */
let queryParams = reactive<FencesPageQuery>({
  "pages": {
    "current": 1,
    "size": 10,
    "startTime": "",
    "endTime": "",
    "orders": [
      {
        "column": "",
        "asc": true
      }
    ]
  },
  "fenceName": "",
  "customerId": customerId,
});
let addFences = reactive<addFencesPageQuery>({
  coordinateSet: [],
  fenceName: "",
});
let editFences = reactive<addFencesPageQuery>({
  coordinateSet: [],
  fenceName: "",
});

// 基本常量
const EARTH_RADIUS = 6378137; // 地球半径，单位：米
/**
 * 根据中心点经纬度和半径计算矩形的四个角点
 * @param {number[]} center - 中心点经纬度 [经度, 纬度]
 * @param {number} radius - 半径，单位：米
 * @returns {number[][]} 矩形的四个角点 [西南角, 西北角, 东南角, 东北角]
 */
function getRectangleCorners(center: number[], radius: number) {
  const [longitude, latitude] = center;
  const radLat = latitude * (Math.PI / 180); // 纬度转换为弧度

  // 纬度变化
  const dLat = radius / EARTH_RADIUS;
  const latDelta = dLat * (180 / Math.PI);

  // 经度变化
  const dLng = radius / (EARTH_RADIUS * Math.cos(radLat));
  const lngDelta = dLng * (180 / Math.PI);

  return [
    [longitude - lngDelta, latitude + latDelta], // 西北角
    [longitude - lngDelta, latitude - latDelta], // 西南角
    [longitude + lngDelta, latitude - latDelta], // 东南角
    [longitude + lngDelta, latitude + latDelta]  // 东北角
  ];
}
// 示例
const center = [116.474595, 40.001321];
const radius = 100; // 100米

const corners = getRectangleCorners(center, radius);

/** 查询 */
function handleQuery() {
  loading.value = true;
  console.log(queryParams, '0000');

  LogAPI.getFences(queryParams)
    .then((data) => {
      pageData.value = data.records;
      queryParams.pages.total = data.total;
      queryParams.pages.current = data.current;
      console.log('分页', data);
    })
    .finally(() => {
      loading.value = false;
    });
}

function addPageQuery() {
  addFences.fenceName = ''
  outerVisible.value = true
  setTimeout(() => {
    setMap([]);
  }, 100)
}

function addSave() {
  if (polyEditor.getTarget()) {
    console.log(polyEditor.getTarget()._opts.path);
    addFences.coordinateSet = polyEditor.getTarget()._opts.path
    // addFences.customerId = '1817813000761716738'
    if (addFences.fenceName.trim().length == 0) {
      return ElMessage.error('请输入围栏名称');
    }
    LogAPI.addSave(addFences)
      .then((data) => {
        console.log('添加', data);
        handleQuery();
        ElMessage.success('添加成功');
        outerVisible.value = false
      })
      .finally(() => {
        outerVisible.value = false

      });
  } else {
    alert('请在地图上双击鼠标或点击鼠标右键完成围栏绘制')
  }

}
function editRow(datas: any) {
  outerVisibleEdit.value = true
  editFences.customerId = datas.customerId
  editFences.id = datas.id
  editFences.coordinateSet = datas.coordinateSet
  editFences.fenceName = datas.fenceName
  console.log(editFences.coordinateSet);

  setMap(editFences.coordinateSet);
}
/**
@date: 2024-08-31 14:23:01
编辑电子围栏
*/
function editSave() {
  if (polyEditor.getTarget()) {
    editFences.coordinateSet = polyEditor.getTarget()._opts.path
    if (editFences.fenceName.trim().length == 0) {
      return ElMessage.error('请输入围栏名称');
    }
    LogAPI.editSave(editFences)
      .then((data) => {
        handleQuery();
        ElMessage.success('编辑成功');
        outerVisibleEdit.value = false
      })
      .finally(() => {
        outerVisibleEdit.value = false

      });
  } else {
    alert('请在地图上双击鼠标或点击鼠标右键完成围栏绘制')
  }
}
/**
@date: 2024-08-31 14:22:46
删除电子围栏
*/
function deleteRow(datas: any) {
  LogAPI.deleteSave(datas.id)
    .then((data) => {
      console.log('添加', data);
      handleQuery();
      ElMessage.success('删除成功');
    })
    .finally(() => {
    });
}

onMounted(() => {
  handleQuery();
});
</script>
<style lang="scss" scoped>
.mrg-lf-10 {
  margin-left: 10px;
}

.fontColor_333 {
  :deep(.el-input__inner) {
    color: #333;
  }
}

.titleMolde {
  font-weight: bold;
  position: relative;
  display: flex;
  padding-left: 15px;
  justify-content: space-between;
  align-items: center;

  &::after {
    content: "";
    width: 8px;
    height: 8px;
    position: absolute;
    left: 4px;
    top: 6px;
    background: #2cdfe5b5;
  }

  &::before {
    content: "";
    width: 8px;
    height: 8px;
    background: #09e0e7;
    position: absolute;
    left: 0;
    top: 2px;
  }

}

.app-container {
  position: relative;
  padding: 10px;

  .allTabContent {
    display: flex;
    align-items: center;
    position: absolute;
    top: 15px;
    right: 0;

    div {
      margin-left: 26px;
      font-weight: 700;

      span {
        margin-left: 8px;
      }
    }
  }
}

.Filters {
  margin: 10px 0;
  display: flex;
  align-items: center;

  .el-segmented {
    --el-segmented-item-selected-color: var(--el-text-color-primary);
    --el-segmented-item-selected-bg-color: #5cadff;
    --el-border-radius-base: 16px;
  }

  &>div {
    margin-right: 5px;
  }
}

.div-container {
  display: flex;
  width: 100%;
  color: #333;

  .div-left-container {
    width: 420px;

    .div_search {}
  }

  .div-right-container {
    width: calc(100% - 420px - 10px);
    margin-left: 10px;
    position: relative;

    #myPageTop {
      position: absolute;
      top: 60px;
      left: 10px;
      z-index: 6;
      background-color: #fff;
      border: 1px solid #ccc;
      padding: 10px;

      #tipinput {
        background-color: #fff;
        color: #333;
        border: 1px solid #ccc;
        padding: 5px;
      }
    }
  }
}
</style>
<style>
.amap-sug-result {
  z-index: 9999 !important;
  color: #333
}
</style>
